package com.User;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;


public class StudentOperation {
	
	public static Student getStudentbyID(int studentID) throws IOException {
		String resource = "mybatisConfig.xml";
		InputStream is = org.apache.ibatis.io.Resources.getResourceAsStream(resource);
		SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
		SqlSession session = sessionFactory.openSession();
		StudentMapper mapper=(StudentMapper)session.getMapper(StudentMapper.class);
		Student student;

		Map paramMap=new HashMap();
	    paramMap.put("UserID",studentID);
	    System.out.println(studentID);
	    student=mapper.getStudents(paramMap).get(0);
	    if (student==null) {
			return null;
		}
	    return student;
	}
	
	public int insertStudent(Student student) throws IOException {
		String resource = "mybatisConfig.xml";
		InputStream is = org.apache.ibatis.io.Resources.getResourceAsStream(resource);
		SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
		SqlSession session = sessionFactory.openSession();
		StudentMapper mapper=(StudentMapper)session.getMapper(StudentMapper.class);
		
		System.out.print(student);
		int rs=mapper.insertStudent(student);
		if (rs>0){
			session.commit();
			session.close();
		}
		else {
			return -1;
		}
		return student.getStuID();	
	}

}
